#include "dbsetwindow.h"
#include "ui_dbsetwindow.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QDebug>
DBSetWindow::DBSetWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DBSetWindow)
{
    ui->setupUi(this);
    initWindow();
}

DBSetWindow::~DBSetWindow()
{
    delete ui;
}
void DBSetWindow::initWindow()
{
    //把所有的数据库类型写入到combox里面
    QStringList dris = QSqlDatabase::drivers();
    ui->deriverComboBox->addItems(dris);

    //给本地ip里面显示ip
    QString name = QHostInfo::localHostName();
    QHostInfo hinfo= QHostInfo::fromName(name);
    QList<QHostAddress> addrs = hinfo.addresses();
    for(auto  addr : addrs)
    {
        if(addr.protocol() == QAbstractSocket::IPv4Protocol)
        {
            ui->ipComboBox->addItem(addr.toString());
        }
    }
}

//点击浏览按钮，找到项目下的db文件，只显示名字和后缀，不显示路径
void DBSetWindow::on_lookButton_clicked()
{
    filename = QFileDialog::getOpenFileName(this,"请选择使用的数据库文件",".",
                                                    "db(*.db)");
    QFileInfo info(filename);
    ui->nameLineEdit->setText(info.fileName());
}

//当选择了QSQLITE模式，用户名和密码的输入框就不让输入，设置为无效
void DBSetWindow::on_deriverComboBox_currentIndexChanged(const QString &arg1)
{
    if(arg1 == "QSQLITE")
    {
        ui->userLineEdit->setEnabled(false);
        ui->passwdLineEdit->setEnabled(false);
    }
    else
    {
        ui->userLineEdit->setEnabled(true);
        ui->passwdLineEdit->setEnabled(true);
    }
}


//打开数据库按钮，设置主机ip，文件完整路径
void DBSetWindow::on_openButton_clicked()
{
    db = QSqlDatabase::addDatabase(ui->deriverComboBox->currentText());
    db.setHostName(ui->ipComboBox->currentText());
    qDebug()<<"filename:"<<filename;
    db.setDatabaseName(filename);
    if (db.isOpen()) {
        db.exec("PRAGMA encoding = 'UTF-8';");
    }
    bool ret = db.open();  //打开数据库是否成功
}
